﻿using Wimm.UI.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Wimm.BusinessLogic.Services;
using Wimm.Common.Interfaces.Utils;
using Wimm.Common;
using Wimm.Common.Entities;
using Wimm.Common.Entities.Utils;
using Windows.System.Threading;
using System.Threading.Tasks;
using Wimm.CustomContols;
using Windows.Storage;
using SQLite;
using Wimm.DAL;
using Wimm.Common.Interfaces.Repositories;
using Wimm.Common.Interfaces.Services;
using Wimm.UI.Login;
using Wimm.UI.ViewModels;
using WIMM.DAL.Repositories;
using DataVirtualization.Toolkit.Charting;
using GalaSoft.MvvmLight.Messaging;
using Wimm.UI.Pages;
using Wimm.DAL.Repositories;

// The Hub Page item template is documented at http://go.microsoft.com/fwlink/?LinkID=321224

namespace Wimm.UI
{
    /// <summary>
    /// A page that displays a grouped collection of items.
    /// </summary>
    public sealed partial class HubPage : Page
    {
        private NavigationHelper navigationHelper;

        /// <summary>
        /// NavigationHelper is used on each page to aid in navigation and 
        /// process lifetime management
        /// </summary>
        public NavigationHelper NavigationHelper
        {
            get { return this.navigationHelper; }
        }


        private MainHubViewModel MainViewModel
        {
            get { return ((App)Application.Current).MainViewModel; }
        }

        public HubPage()
        {
            this.InitializeComponent();
            this.DataContext = MainViewModel;
           
            this.hubMain.SizeChanged += hubMain_SizeChanged;

            this.navigationHelper = new NavigationHelper(this);
            this.navigationHelper.LoadState += navigationHelper_LoadState;
        }

        void hubMain_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            this.expensesHub.Width = this.hubMain.ActualWidth;
            this.expensesHub.Height = this.hubMain.ActualHeight;
            this.incomeHub.Width = this.hubMain.ActualWidth;
            this.incomeHub.Height = this.hubMain.ActualHeight;
        }

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="sender">
        /// The source of the event; typically <see cref="NavigationHelper"/>
        /// </param>
        /// <param name="e">Event data that provides both the navigation parameter passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested and
        /// a dictionary of state preserved by this page during an earlier
        /// session.  The state will be null the first time a page is visited.</param>
        private void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
        {
            
        }

        /// <summary>
        /// Invoked when a HubSection header is clicked.
        /// </summary>
        /// <param name="sender">The Hub that contains the HubSection whose header was clicked.</param>
        /// <param name="e">Event data that describes how the click was initiated.</param>
        void Hub_SectionHeaderClick(object sender, HubSectionHeaderClickEventArgs e)
        {
            HubSection section = e.Section;
            var group = section.DataContext;
        }

        /// <summary>
        /// Invoked when an item within a section is clicked.
        /// </summary>
        /// <param name="sender">The GridView or ListView
        /// displaying the item clicked.</param>
        /// <param name="e">Event data that describes the item clicked.</param>
        void ItemView_ItemClick(object sender, ItemClickEventArgs e)
        {
        }

        #region NavigationHelper registration

        /// The methods provided in this section are simply used to allow
        /// NavigationHelper to respond to the page's navigation methods.
        /// 
        /// Page specific logic should be placed in event handlers for the  
        /// <see cref="GridCS.Common.NavigationHelper.LoadState"/>
        /// and <see cref="GridCS.Common.NavigationHelper.SaveState"/>.
        /// The navigation parameter is available in the LoadState method 
        /// in addition to page state preserved during an earlier session.

        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            if (e.Parameter is User)
            {
                this.MainViewModel.LogedUser = (User)e.Parameter;
                await this.MainViewModel.AsyncGroupIncomes();
                await this.MainViewModel.AsyncGroupExpenses();
            }
            navigationHelper.OnNavigatedTo(e);
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            navigationHelper.OnNavigatedFrom(e);
        }

        #endregion

        private void HomeAppBarButton_Click(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(HubPage));
        }

        private void TextBox_Loaded(object sender, RoutedEventArgs e)
        {
            ((TextBox)sender).Text = SqlLightBaseRepository.DbPath;
        }

        private void AddExpensesAppBarButton_Click(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(AddExpensePage),this.MainViewModel.AddExpenseViewModel);

        }

        private async void YearDiagram_Click(object sender, RoutedEventArgs e)
        {
            this.MainViewModel.YearDiagramVM.SetChartSeries(
                await this.MainViewModel.GetYearlyExpenseDiagramData(),
                await this.MainViewModel.GetYearlyIncomeDiagramData()
                );
            this.Frame.Navigate(typeof(YearDiagram), this.MainViewModel.YearDiagramVM);
        }
        private void AddIncomesButton_Click(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(AddIncomePage),this.MainViewModel.AddIncomeViewModel);
        }

        private void Calendar_Click(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof (PageCalendar));
        }

        private async void ExpensePieChart_Loaded(object sender, RoutedEventArgs e)
        {
            PieChart chart = sender as PieChart;
            if (chart != null)
            {
                await this.MainViewModel.AsyncGroupExpenses();
                this.MainViewModel.UpdateExpenseCategories();
                _chart = chart;
                chart.ItemsSource = this.MainViewModel.ExpensesDiagramSource;
            }
        }
        private async void IncomePieChart_Loaded(object sender, RoutedEventArgs e)
        {
            PieChart chart = sender as PieChart;
            if (chart != null)
            {
                await this.MainViewModel.AsyncGroupIncomes();
                this.MainViewModel.UpdateIncomesCategories();
                _chart = chart;
                chart.ItemsSource = this.MainViewModel.IncomesDiagramSource;
            }
        }

        private PieChart _chart;

        private void Grid_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            if (_chart != null)
            {
                _chart.ItemsSource = null;
                _chart.ItemsSource = this.MainViewModel.ExpensesDiagramSource;
            }
        }

        private async void EnglishLanguageButton_Click(object sender, RoutedEventArgs e)
        {
            this.MainViewModel.Language = "en-US";
            await LanguageUpdate();
        }
        private async void RussianLanguageButton_Click(object sender, RoutedEventArgs e)
        {
            this.MainViewModel.Language = "ru-RU";
            await LanguageUpdate();
        }
        private async void UkraineLanguageButton_Click(object sender, RoutedEventArgs e)
        {
            this.MainViewModel.Language = "uk-UA";
            await LanguageUpdate();
        }
        private async void FranceLanguageButton_Click(object sender, RoutedEventArgs e)
        {
            this.MainViewModel.Language = "fr-FR";
            await LanguageUpdate();
        }

        private async Task LanguageUpdate()
        {
            Windows.Globalization.ApplicationLanguages.PrimaryLanguageOverride = this.MainViewModel.Language;
            Windows.ApplicationModel.Resources.Core.ResourceContext.GetForViewIndependentUse().Reset();
            Windows.ApplicationModel.Resources.Core.ResourceManager.Current.DefaultContext.Reset();
            this.MainViewModel.AddExpenseViewModel.SetLanguage(this.MainViewModel.Language);
            this.MainViewModel.AddIncomeViewModel.SetLanguage(this.MainViewModel.Language);
            this.MainViewModel.ExpensesFilterData.SetFilterLang(this.MainViewModel.Language);
            this.MainViewModel.IncomesFilterData.SetFilterLang(this.MainViewModel.Language);
            await this.MainViewModel.InitModelDataAsync();
            this.Frame.Navigate(typeof(HubPage));
        }
    }
}
